//
//  MRequestManage.m
//  MApiSample
//
//  Created by IOS_HMX on 17/2/16.
//  Copyright © 2017年 Mitake. All rights reserved.
//

#import "MRequestManage.h"
static BOOL kIsSuccess;
static NSMutableArray *kRequestArray;

@interface MReq : NSObject
@property (nonatomic, strong) MRequest *request;
@property (nonatomic , copy) MApiCompletionHandler handler;
@property (nonatomic , copy) MApTimeoutHandler timeoutHandler;

@end
@implementation MReq
@end
@implementation MRequestManage
+ (void)initialize
{
    kRequestArray = [NSMutableArray array];
    kIsSuccess = false;
}
+ (void)sendRequest:(MRequest *)request completionHandler:(MApiCompletionHandler)handler
{
    [self sendRequest:request completionHandler:handler timeoutHandler:nil];
}
+ (void)sendRequest:(MRequest *)request completionHandler:(MApiCompletionHandler)handler timeoutHandler:(MApTimeoutHandler)timeoutHandler
{
    if (kIsSuccess) {
        NSLog(@"\n send \n%@\n",request);
        [MApi sendRequest:request completionHandler:handler timeoutHandler:timeoutHandler];
    }else {
        MReq *req = [[MReq alloc]init];
        req.request = request;
        req.handler = handler;
        req.timeoutHandler = timeoutHandler;
        [kRequestArray addObject:req];
        
        [MApi registerAPP:@"sjX0AC7vQcOe4frso/6XuRP+ag4nLa7i28T16pZyywY=" withOptions:nil sourceLevel:MApiSourceLevel1 completionHandler:^(NSError *error) {
            if (error) {
                [self errorRequest:error];
            }else {
                kIsSuccess = true;
                [self resendRequests];
            }
        }];
        
    }
}
+ (void)registerSuccess
{
    kIsSuccess = true;
    [self resendRequests];
}
+ (void)cancelAllRequests
{
    [MApi cancelAllRequests];
    [kRequestArray removeAllObjects];
    
}
+ (void)cancelRequest:(MRequest *)request
{
    [MApi cancelRequest:request];
    NSMutableArray *temp = [kRequestArray copy];
    for (MReq *req in temp) {
        if ([req.request isEqual:request]) {
            [kRequestArray removeObject:req];
            NSLog(@"\n cancel \n%@\n",((MSnapQuoteRequest *)req.request).code);
        }
    }
    
}
+ (void)resendRequests
{
    NSMutableArray *temp = [kRequestArray copy];
    for (MReq *req in temp) {
        NSLog(@"\n resend \n%@\n",((MSnapQuoteRequest *)req.request).code);
        [MApi sendRequest:req.request completionHandler:req.handler timeoutHandler:req.timeoutHandler];
        [kRequestArray removeObject:req];
    }
}
+ (void)errorRequest:(NSError *)error
{
    NSMutableArray *temp = [kRequestArray copy];
    for (MReq *req in temp) {
        MResponse *response = [[MResponse alloc]init];
        response.status = error.code;
        req.handler(response);
        [kRequestArray removeObject:req];
    }
}
@end
